/*
========================================================================
 Name        : PublicTransportMapContainerView.cpp
 Author      : 
 Copyright   : Your copyright notice
 Description : 
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <aknviewappui.h>
#include <eikmenub.h>
#include <avkon.hrh>
#include <akncontext.h>
#include <akntitle.h>
#include <stringloader.h>
#include <barsread.h>
#include <eikbtgpc.h>
#include <SingaporeBus.rsg>
// ]]] end generated region [Generated System Includes]

#include <aknnavilabel.h>
#include <aknlists.h>
#include <aknpopup.h>
#include <ImageConversion.h>
#include "SingaporeBusDocument.h"
#include "SingaporeBusAppUi.h"
#include "CharUtils.h"
#include <SingaporeBus.mbg>
#include <S32FILE.H>
#include <aknglobalnote.h>
#include "CSingaporeBusGenericView.hrh"

// [[[ begin generated region: do not modify [Generated User Includes]

#include "SingaporeBus.hrh"
#include "PublicTransportMapContainerView.h"
#include "PublicTransportMapContainer.hrh"
#include "SingaporeBusSettingItemList.hrh"
#include "SingaporeBusAccessPointsPriorityListBox.hrh"
#include "CSingaporeBusStopsView.hrh"
#include "CSingaporeBusServicesArrivalTimeView.hrh"
#include "CSingaporeBusRouteView.hrh"
#include "CSingaporeBusServiceRouteView.hrh"
#include "CSingaporeBusServicesView.hrh"
#include "CSingaporeBusFavoritesView.hrh"
#include "PublicTransportMapContainer.h"
// ]]] end generated region [Generated User Includes]

#include "ImageDecoderEx.h"
#include "MapUtils.h"

// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]


static void PrintNoteL(TRefByValue<const TDesC> aFormat, ...)
    {
    VA_LIST list;
    VA_START(list, aFormat);
    TBuf<256> buf;
    buf.FormatList(aFormat, list);
    VA_END(list);
	CAknGlobalNote* globalNote = CAknGlobalNote::NewLC();
	globalNote->ShowNoteL(EAknGlobalInformationNote, buf); 
    CleanupStack::PopAndDestroy(globalNote);
    }

/**
 * First phase of Symbian two-phase construction. Should not contain any
 * code that could leave.
 */
CPublicTransportMapContainerView::CPublicTransportMapContainerView()
	{
	TFunTrace funTrace(__PRETTY_FUNCTION__);
	// [[[ begin generated region: do not modify [Generated Contents]
	iPublicTransportMapContainer = NULL;
	// ]]] end generated region [Generated Contents]
	iZoomLevel = 5;
	iOrig = TCoordinate(1.31623, 103.76506);

	}

/** 
 * The view's destructor removes the container from the control
 * stack and destroys it.
 */
CPublicTransportMapContainerView::~CPublicTransportMapContainerView()
	{
	TFunTrace funTrace(__PRETTY_FUNCTION__);
	
	// [[[ begin generated region: do not modify [Generated Contents]
	delete iPublicTransportMapContainer;
	iPublicTransportMapContainer = NULL;
	// ]]] end generated region [Generated Contents]
	iStationsOrderedByLongitude.Close();
	iServicePaths.Close();
	for(TInt i = 0 ; i < iDisplayServiceKeys.Count() ; ++i)
		delete iDisplayServiceKeys[i];
	iDisplayServiceKeys.Close();
	//CImageDecoderEx::StopThread();
	}

void CPublicTransportMapContainerView::NotifyConnected()
	{
	TFunTrace funTrace(__PRETTY_FUNCTION__);
	
	}

CPublicTransportMapContainerView::CViewState* CPublicTransportMapContainerView::GetViewStateLC()
	{
	TFunTrace funTrace(__PRETTY_FUNCTION__);
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	CViewState* viewState = new (ELeave) CViewState;
	CleanupStack::PushL(viewState);
	viewState->iOrig = iOrig;
	viewState->iZoomLevel = iZoomLevel;
	viewState->iSelectedStation = iSelectedStation;
	viewState->iSelectedService = iSelectedService;
	for(TInt i = 0 ; i < iDisplayServiceKeys.Count() ; ++i)
		viewState->iDisplayServiceKeys.AppendL(iDisplayServiceKeys[i]->AllocL());
	viewState->iCurrentDisplayServiceKey = iCurrentDisplayServiceKey;
	viewState->iDisplayRouteSteps = iDisplayRouteSteps;
	for(TInt i = 0 ; i < iServicePaths.Count() ; ++i)
		viewState->iServicePaths.AppendL(iServicePaths[i]);
	return viewState;
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance then calls the second-phase constructor
 * without leaving the instance on the cleanup stack.
 * @return new instance of CPublicTransportMapContainerView
 */
CPublicTransportMapContainerView* CPublicTransportMapContainerView::NewL()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CPublicTransportMapContainerView* self = CPublicTransportMapContainerView::NewLC();
	CleanupStack::Pop( self );
	return self;
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance, pushes it on the cleanup stack,
 * then calls the second-phase constructor.
 * @return new instance of CPublicTransportMapContainerView
 */
CPublicTransportMapContainerView* CPublicTransportMapContainerView::NewLC()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CPublicTransportMapContainerView* self = new ( ELeave ) CPublicTransportMapContainerView();
	CleanupStack::PushL( self );
	self->ConstructL();
	return self;
	}

/**
 * Second-phase constructor for view.  
 * Initialize contents from resource.
 */ 
void CPublicTransportMapContainerView::ConstructL()
	{
	//CImageDecoderEx::StartThread();
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// [[[ begin generated region: do not modify [Generated Code]
	BaseConstructL( R_PUBLIC_TRANSPORT_MAP_CONTAINER_PUBLIC_TRANSPORT_MAP_CONTAINER_VIEW );
				
	// ]]] end generated region [Generated Code]
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	doc->iMapTileServer->SetCallback( scalp::MakeFunctionL(scalp::Bind(&CPublicTransportMapContainerView::RedrawMap, this)) );
	}



/**
 * @return The UID for this view
 */
TUid CPublicTransportMapContainerView::Id() const
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	return TUid::Uid( EPublicTransportMapContainerViewId );
	}

/**
 * Handle a command for this view (override)
 * @param aCommand command id to be handled
 */
void CPublicTransportMapContainerView::HandleCommandL( TInt aCommand )
	{
	// [[[ begin generated region: do not modify [Generated Code]
	TBool commandHandled = EFalse;
	switch ( aCommand )
		{	// code to dispatch to the AknView's menu and CBA commands is generated here
		case EPublicTransportMapContainerViewShow_busMenuItemCommand:
			commandHandled = HandleShow_busMenuItemSelectedL( aCommand );
			break;
		case EPublicTransportMapContainerViewRefresh_positionMenuItemCommand:
			commandHandled = HandleRefresh_positionMenuItemSelectedL( aCommand );
			break;
		case EPublicTransportMapContainerViewOriginMenuItemCommand:
			commandHandled = HandleMarkOriginMenuItemSelectedL( aCommand );
			break;
		case EPublicTransportMapContainerViewDestinationMenuItemCommand:
			commandHandled = HandleMarkDestinationMenuItemSelectedL( aCommand );
			break;
		case EPublicTransportMapContainerViewFavoriteMenuItemCommand:
			commandHandled = HandleMarkFavoriteMenuItemSelectedL( aCommand );
			break;
		default:
			break;
		}
	
		
	if ( !commandHandled ) 
		{
	
		}
	// ]]] end generated region [Generated Code]
	if ( !commandHandled ) 
		{
	
		AppUi()->HandleCommandL(aCommand);
	
		}
	
	}


void CPublicTransportMapContainerView::StoreViewStateL(TDes8& aCustomMessage)
	{
	TFunTrace funTrace(__PRETTY_FUNCTION__);
	StoreCustomMessageParamL(aCustomMessage, _L8("lat"), _L8("%F"), iOrig.Latitude());
	StoreCustomMessageParamL(aCustomMessage, _L8("lon"), _L8("%F"), iOrig.Longitude());
	StoreCustomMessageParamL(aCustomMessage, _L8("zoom"), _L8("%d"), iZoomLevel);
	if(iSelectedStation)
		StoreCustomMessageParamL(aCustomMessage, _L8("station"), _L8("%S"), &iSelectedStation->iStationNumber);
	if(iSelectedService)
		StoreCustomMessageParamL(aCustomMessage, _L8("service"), _L8("%S"), &iSelectedService->iServiceKey);
	StoreCustomMessageParamL(aCustomMessage, _L8("curpath"), _L8("%d"), iCurrentDisplayServiceKey);
	for(TInt i = 0 ; i < iDisplayServiceKeys.Count() ; ++i)
		StoreCustomMessageParamL(aCustomMessage, _L8("path"), _L8("%S"), iDisplayServiceKeys[i]);
	}

void CPublicTransportMapContainerView::RestoreViewStateL(const TDesC8& aCustomMessage)
	{
	TFunTrace funTrace(__PRETTY_FUNCTION__);
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	for(TInt i = 0 ; i < iDisplayServiceKeys.Count() ; ++i)
		delete iDisplayServiceKeys[i];
	iDisplayServiceKeys.Reset();
	iSelectedService = NULL;
	iSelectedStation = NULL;
	TPtrC8 field, value, remainder(aCustomMessage);
	while(ParseCustomMessageParamL(field, value, remainder))
		{
		if(field == _L8("lat"))
			{
			TLex8 lex(value);
			TReal64 real; lex.Val(real);
			iOrig.SetCoordinate(real, iOrig.Longitude());
			}
		else if(field == _L8("lon"))
			{
			TLex8 lex(value);
			TReal64 real; lex.Val(real);
			iOrig.SetCoordinate(iOrig.Latitude(), real);
			}
		else if(field == _L8("zoom"))
			{
			TLex8 lex(value);
			lex.Val(iZoomLevel);
			}
		else if(field == _L8("station"))
			{
			TStation target = { value };
			TInt ret = doc->iStationsSortedByStationNumber.SpecificFindInOrder(&target, TLinearOrder<const TStation*>(&CSingaporeBusDocument::TLinearOrder_Station), EArrayFindMode_Any);
			iSelectedStation = (ret != KErrNotFound) ? doc->iStationsSortedByStationNumber[ret] : NULL;
			}
		else if(field == _L8("service"))
			{
			CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
			TBuf8<15> strServiceKeyUpper(value);
			strServiceKeyUpper.UpperCase();
			TService target = { strServiceKeyUpper };
			TInt ret = doc->iServicesSortedByServiceKey.SpecificFindInOrder(&target, TLinearOrder<const TService*>(&CSingaporeBusDocument::TLinearOrder_Service), EArrayFindMode_Any);
			iSelectedService = (ret != KErrNotFound) ? doc->iServicesSortedByServiceKey[ret] : NULL;
			}
		else if(field == _L8("path"))
			{
			iDisplayServiceKeys.AppendL(value.AllocL());
			}
		else if(field == _L8("curpath"))
			{
			TLex8 lex(value);
			lex.Val(iCurrentDisplayServiceKey);
			}
		}
	}

/**
 *	Handles user actions during activation of the view, 
 *	such as initializing the content.
 */
void CPublicTransportMapContainerView::DoActivateL( 
		const TVwsViewId& aPrevViewId,
		TUid aCustomMessageId,
		const TDesC8& aCustomMessage )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);

if(1 == 0)
{
CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
doc->iLogFile.Write(_L8("enter CPublicTransportMapContainerView::DoActivateL\n"));
doc->iLogFile.Flush();
}

TLex8 customMessageLex(aCustomMessage);
TInt customMessageInt;
customMessageLex.Val(customMessageInt);
LCleanedupPtr<CViewState> backViewState ( (aCustomMessageId.iUid == EAknSoftkeyBack) ? (CViewState*)reinterpret_cast<CBase*>(customMessageInt) : NULL );

RestoreViewStateL(aCustomMessage);

//static_cast<CSingaporeBusAppUi*>(CEikonEnv::Static()->AppUi())->SwitchCustomLayout1(StatusPane());
#define SetupStatusPaneL() ;
	// [[[ begin generated region: do not modify [Generated Contents]
	SetupStatusPaneL();
	
				
	if ( iPublicTransportMapContainer == NULL )
		{
		iPublicTransportMapContainer = CreateContainerL();
		iPublicTransportMapContainer->SetMopParent( this );
		AppUi()->AddToStackL( *this, iPublicTransportMapContainer );
		} 
	// ]]] end generated region [Generated Contents]
#undef SetupStatusPaneL
	iPrevViewId = aPrevViewId;
	if(1 == 0)
	{
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	doc->iLogFile.Write(_L8("leave CPublicTransportMapContainerView::DoActivateL\n"));
	doc->iLogFile.Flush();
	}
	
	}

/**
 */
void CPublicTransportMapContainerView::DoDeactivate()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// [[[ begin generated region: do not modify [Generated Contents]
	CleanupStatusPane();
	
	if ( iPublicTransportMapContainer != NULL )
		{
		AppUi()->RemoveFromViewStack( *this, iPublicTransportMapContainer );
		delete iPublicTransportMapContainer;
		iPublicTransportMapContainer = NULL;
		}
	// ]]] end generated region [Generated Contents]

	{
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();		
	}
	
	}

/** 
 * Handle status pane size change for this view (override)
 */
void CPublicTransportMapContainerView::HandleStatusPaneSizeChange()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CAknView::HandleStatusPaneSizeChange();
	
	// this may fail, but we're not able to propagate exceptions here
	TVwsViewId view;
	AppUi()->GetActiveViewId( view );
	if ( view.iViewUid == Id() )
		{
		TInt result;
		TRAP( result, SetupStatusPaneL() );
		UpdateTitle();
		}
	
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	}

void CPublicTransportMapContainerView::OverrideSetupStatusPaneL()
	{
	/*
	// reset the context pane
	TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext );
	CEikStatusPaneBase::TPaneCapabilities subPaneContext = 
		StatusPane()->PaneCapabilities( contextPaneUid );
	if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() )
		{
		CAknContextPane* context = static_cast< CAknContextPane* > ( 
			StatusPane()->ControlL( contextPaneUid ) );
		context->SetPictureToDefaultL();
		}
	
	// set the navi pane content
	TUid naviPaneUid = TUid::Uid( EEikStatusPaneUidNavi );
	CEikStatusPaneBase::TPaneCapabilities subPaneNavi = 
		StatusPane()->PaneCapabilities( naviPaneUid );
	if ( subPaneNavi.IsPresent() && subPaneNavi.IsAppOwned() )
		{
		CAknNavigationControlContainer* naviPane = 
			static_cast< CAknNavigationControlContainer* >( 
				StatusPane()->ControlL( naviPaneUid ) );
		if ( iNaviDecorator_ != NULL )
			{
			delete iNaviDecorator_;
			iNaviDecorator_ = NULL;
			}
		iNaviDecorator_ = naviPane->CreateNavigationLabelL(KNullDesC);
				
		naviPane->PushL( *iNaviDecorator_ );
		}
	
	UpdateTitle();*/
				
	}


// [[[ begin generated function: do not modify
void CPublicTransportMapContainerView::SetupStatusPaneL()
	{
	// reset the context pane
	TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext );
	CEikStatusPaneBase::TPaneCapabilities subPaneContext = 
		StatusPane()->PaneCapabilities( contextPaneUid );
	if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() )
		{
		CAknContextPane* context = static_cast< CAknContextPane* > ( 
			StatusPane()->ControlL( contextPaneUid ) );
		context->SetPictureToDefaultL();
		}
	
	// setup the title pane
	TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle );
	CEikStatusPaneBase::TPaneCapabilities subPaneTitle = 
		StatusPane()->PaneCapabilities( titlePaneUid );
	if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() )
		{
		CAknTitlePane* title = static_cast< CAknTitlePane* >( 
			StatusPane()->ControlL( titlePaneUid ) );
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_PUBLIC_TRANSPORT_MAP_CONTAINER_TITLE_RESOURCE );
		title->SetFromResourceL( reader );
		CleanupStack::PopAndDestroy(); // reader internal state
		}
				
	}

// ]]] end generated function

// [[[ begin generated function: do not modify
void CPublicTransportMapContainerView::CleanupStatusPane()
	{
	}

// ]]] end generated function

/**
 *	Creates the top-level container for the view.  You may modify this method's
 *	contents and the CPublicTransportMapContainer::NewL() signature as needed to initialize the
 *	container, but the signature for this method is fixed.
 *	@return new initialized instance of CPublicTransportMapContainer
 */
CPublicTransportMapContainer* CPublicTransportMapContainerView::CreateContainerL()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	return CPublicTransportMapContainer::NewL( ClientRect(), NULL, this );
	}

void CPublicTransportMapContainerView::UpdateTitle()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();		
	CAknTitlePane* title = static_cast< CAknTitlePane* >( 
		StatusPane()->ControlL( TUid::Uid( EEikStatusPaneUidTitle ) ) );

	TBuf<256> buf;
	
	if(iSelectedStation)
		{
		buf.AppendFormat(_L("%S\n%S"),
				narrowToWideLC(iSelectedStation->iAddress2), narrowToWideLC(iSelectedStation->iAddress)
				);
		CleanupStack::PopAndDestroy(2); // narrowToWideLC(iSelectedStation->iAddress2), narrowToWideLC(iSelectedStation->iAddress)
		}
	buf.AppendFormat( _L(" (%S)"), &doc->PositionDescription() );
	title->SetTextL(buf, ETrue);
	}


void CPublicTransportMapContainerView::NotifyPositionChange()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	if ( iPublicTransportMapContainer )
		{
		UpdateTitle();
		CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
		if(iPublicTransportMapContainer->iPositionTracking && doc->iPositioningStatus == CSingaporeBusDocument::PS_FOUND)
			iPublicTransportMapContainer->CenterMapOn(doc->iPosition);
		iPublicTransportMapContainer->DrawToBackBuffer();
		iPublicTransportMapContainer->DrawDeferred();
		}
	}

void CPublicTransportMapContainerView::NotifyAzimuthChange()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	if ( iPublicTransportMapContainer )
		{
		iPublicTransportMapContainer->DrawToBackBuffer();
		iPublicTransportMapContainer->DrawDeferred();
		}
	}

/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleMapMenuItemSelectedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// TODO: implement selected event handler
	((CSingaporeBusAppUi*)iAvkonViewAppUi)->PushBackViewL(Id(), TUid::Uid(EAknSoftkeyBack), GetViewStateLC());
	CleanupStack::Pop();
	static_cast<CAknViewAppUi*>(CEikonEnv::Static()->AppUi())->ActivateLocalViewL(
			TUid::Uid(ESingaporeBusStopsViewId)
		);					
	return ETrue;
	}


static TInt SelectServiceL(TPtrC8& aServiceKey)
	{
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	
	TInt stack=0;
	// Make listitems. and PUSH it
	CAknSinglePopupMenuStyleListBox* list = new(ELeave) CAknSinglePopupMenuStyleListBox;
	CleanupStack::PushL(list);
	stack++;
  	// Create popup list and PUSH it.
	CAknPopupList* popupList = CAknPopupList::NewL(list, R_AVKON_SOFTKEYS_OK_CANCEL, AknPopupLayouts::EMenuWindow);
	CleanupStack::PushL(popupList);
	stack++;
  	CDesCArrayFlat* items = new (ELeave) CDesCArrayFlat(5);
	CleanupStack::PushL(items);
	stack++;
 	// initialize listbox.
	list->ConstructL(popupList, CEikListBox::ELeftDownInViewRect | EAknListBoxMarkableList);
	list->CreateScrollBarFrameL(ETrue);
	list->ScrollBarFrame()->SetScrollBarVisibilityL(CEikScrollBarFrame::EOff, CEikScrollBarFrame::EAuto);

	{
		RBuf8 buf;
		CleanupClosePushL(buf);
		buf.CreateL(1024);
		for( TInt i = 0 ; i < doc->iServices.Count() ; ++i )
			{
			const TDesC8& serviceKey = doc->iServices[i].iServiceKey;
			TPtrC8 serviceName = serviceKey.Left( serviceKey.Locate(' ') );
			_LIT8(kFormat, "%S to %S");
			buf.Format(kFormat, &serviceName, &doc->iServices[i].iTo);
			items->AppendL(*narrowToWideLC(buf));
			CleanupStack::PopAndDestroy(); // narrowToWideLC(buf)
			}
		CleanupStack::PopAndDestroy(); // buf
	}
	
	
  	// Set listitems.
	CTextListBoxModel* model = list->Model();
	model->SetItemTextArray(items);
	model->SetOwnershipType(ELbmOwnsItemArray);
	CleanupStack::Pop();
    popupList->SetTitleL(_L("Services"));
	list->SetListBoxObserver(popupList);
	list->ItemDrawer()->FormattedCellData()->EnableMarqueeL(ETrue);
	popupList->EnableFind(ETrue);
	TInt popupOk = popupList->ExecuteLD();
	CleanupStack::Pop();
	if (popupOk)
		{
		aServiceKey.Set(doc->iServices[ list->CurrentItemIndex() ].iServiceKey );
		}
	CleanupStack::PopAndDestroy();
	return popupOk;
}

/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleShow_busMenuItemSelectedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// TODO: implement selected event handler
	TPtrC8 serviceKey;
	if(SelectServiceL(serviceKey))
		{
		CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
		
		{
		for(TInt i = 0 ; i < iDisplayServiceKeys.Count() ; delete iDisplayServiceKeys[i++]);
		iDisplayServiceKeys.Reset();
		iDisplayServiceKeys.AppendL(serviceKey.AllocL());
		iCurrentDisplayServiceKey = 0;
		iPublicTransportMapContainer->LoadCurrentDisplayServiceL();
		}
		
		iPublicTransportMapContainer->DrawToBackBuffer();
		iPublicTransportMapContainer->DrawDeferred();
		}
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleExitMenuItemSelectedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	AppUi()->HandleCommandL( EEikCmdExit );
	return ETrue;
	}
				
/** 
 * Handle the rightSoftKeyPressed event.
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleControlPaneRightSoftKeyPressedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	((CSingaporeBusAppUi*)iAvkonViewAppUi)->PushBackViewL(Id(), TUid::Uid(EAknSoftkeyBack), GetViewStateLC());
	CleanupStack::Pop();
	static_cast<CAknViewAppUi*>(CEikonEnv::Static()->AppUi())->ActivateLocalViewL(
			TUid::Uid(ESingaporeBusStopsViewId)
		);					
	//static_cast<CAknViewAppUi*>(CEikonEnv::Static()->AppUi())->ActivateLocalViewL(iPrevViewId.iViewUid);
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleRefresh_positionMenuItemSelectedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// TODO: implement selected event handler
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	doc->RefreshPosition();
	UpdateTitle();
	return ETrue;
	}

static TInt TLinearOrder_Station(const TStation* const& left, const TStation* const& right)
	{
	if (left->iCoord.Longitude() < right->iCoord.Longitude()) return -1;
	if (left->iCoord.Longitude() == right->iCoord.Longitude()) return 0;
	return 1;
	}

void CPublicTransportMapContainerView::NotifyFileLoaded(const CAsyncFileLoader* aFile)
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	if(aFile == doc->iServicesFileLoader) // note: we wait for the services to load so that there's not too much processing when stations are loaded
		{
		iStationsOrderedByLongitude.Reset();
		iStationsOrderedByLongitude.Reserve(doc->iStations.Count());
		for(TInt i = 0 ; i < doc->iStations.Count() ; ++i )
			iStationsOrderedByLongitude.AppendL( &doc->iStations[i] );
		iStationsOrderedByLongitude.Sort(TLinearOrder<const TStation*>(&TLinearOrder_Station));
		if(iPublicTransportMapContainer)
			{
			iPublicTransportMapContainer->RefreshVisibleStationsL();
			iPublicTransportMapContainer->DrawToBackBuffer();
			iPublicTransportMapContainer->DrawDeferred();
			}
		}	
	else if(aFile == doc->iServicesPathsFileLoader && iPublicTransportMapContainer)
		{
		iPublicTransportMapContainer->DrawToBackBuffer();
		iPublicTransportMapContainer->DrawDeferred();
		}
	}


static TInt TLinearOrder_TPtrC8(const TPtrC8& left, const TPtrC8& right)
	{
	return left.Compare(right);
	}

/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleMarkFavoriteMenuItemSelectedL( TInt aCommand )
	{
	TFunTrace funTrace(__PRETTY_FUNCTION__);
		CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
		
		if(iSelectedStation)
			CSingaporeBusGenericHandler::HandleCommandL(iSelectedStation, ESingaporeBusMarkFavorite);
		iPublicTransportMapContainer->DrawToBackBuffer();
		iPublicTransportMapContainer->DrawDeferred();
		
		return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleMarkOriginMenuItemSelectedL( TInt aCommand )
	{
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	if(iSelectedStation)
		CSingaporeBusGenericHandler::HandleCommandL(iSelectedStation, ESingaporeBusMarkOrigin);
	iPublicTransportMapContainer->DrawToBackBuffer();
	iPublicTransportMapContainer->DrawDeferred();

	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleMarkDestinationMenuItemSelectedL( TInt aCommand )
	{
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	if(iSelectedStation)
		CSingaporeBusGenericHandler::HandleCommandL(iSelectedStation, ESingaporeBusMarkDestination);
	iPublicTransportMapContainer->DrawToBackBuffer();
	iPublicTransportMapContainer->DrawDeferred();

	return ETrue;
	}
								
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleViewListMenuItemSelectedL( TInt aCommand )
	{
	((CSingaporeBusAppUi*)iAvkonViewAppUi)->PushBackViewL(Id(), TUid::Uid(EAknSoftkeyBack), GetViewStateLC());
	CleanupStack::Pop();
	static_cast<CAknViewAppUi*>(CEikonEnv::Static()->AppUi())->ActivateLocalViewL(
			TUid::Uid(ESingaporeBusStopsViewId)
		);					
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CPublicTransportMapContainerView::HandleViewRouteMenuItemSelectedL( TInt aCommand )
	{
	((CSingaporeBusAppUi*)iAvkonViewAppUi)->PushBackViewL(Id(), TUid::Uid(EAknSoftkeyBack), GetViewStateLC());
	CleanupStack::Pop();
	static_cast<CAknViewAppUi*>(CEikonEnv::Static()->AppUi())->ActivateLocalViewL(
			TUid::Uid(ESingaporeBusRouteViewId)
		);					
	return ETrue;
	}
				
CCoeControl* CPublicTransportMapContainerView::iContainer()
	{
	return iPublicTransportMapContainer;
	}

void CPublicTransportMapContainerView::RedrawMap()
	{
	if(iPublicTransportMapContainer)
		{
		iPublicTransportMapContainer->DrawToBackBuffer();
		iPublicTransportMapContainer->DrawDeferred();
		}
	}
